﻿using System;
using System.Windows;
using System.Windows.Media;
using System.Device.Location;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Tasks;
using System.Windows.Media.Imaging;
using System.IO;
using System.IO.IsolatedStorage;
using Microsoft.Xna.Framework.Media;
using ExifLib;
using Coding4Fun.Phone.Controls;
using System.Net;
using System.Linq;
using System.Xml.Linq;

namespace geopg_wp7
{
    public partial class MainPage : PhoneApplicationPage
    {
        // Declare the CameraCaptureTask object with page scope.
        CameraCaptureTask cameraCaptureTask;
        PhotoChooserTask photoChooserTask;
        BitmapImage bmp;
        String titleinput;
        String descinput;
        public static PhotoResult chosenimg;

        // Constructor
        public MainPage()
        {
            InitializeComponent();

            // Initialize the CameraCaptureTask and assign the Completed handler in the page constructor.
            cameraCaptureTask = new CameraCaptureTask();
            cameraCaptureTask.Completed += new EventHandler<PhotoResult>(photoCaptureOrSelectionCompleted);
            photoChooserTask = new PhotoChooserTask();
            photoChooserTask.Completed += new EventHandler<PhotoResult>(photoCaptureOrSelectionCompleted);
        }

        /*public static JpegInfo ReadJpeg(Stream FileStream, string FileName)
        {
            DateTime now = DateTime.Now;
            ExifReader reader = new ExifReader();
            reader.info.FileSize = (int)FileStream.Length;
            reader.info.FileName = string.Format("{0}.jpg", FileName);
            reader.info.LoadTime = (TimeSpan)(DateTime.Now - now);
            return reader.info;
    }*/


        // Event-Handling (Photo wird als BitmapImage gespeichert - Button-States werden geändert.
        void photoCaptureOrSelectionCompleted(object sender, PhotoResult e)
        {
            if (e.TaskResult == TaskResult.OK)
            {
                // Read EXIF-Data
                JpegInfo info = ExifReader.ReadJpeg(e.ChosenPhoto, e.OriginalFileName);
                GlobalVariables.photores = e;
                chosenimg = e;
                bmp = new BitmapImage();
                bmp.SetSource(e.ChosenPhoto);
                myImage.Source = bmp;
                myImage.Stretch = Stretch.Uniform;

                // swap UI element states
                takePhotoButton.Visibility = Visibility.Collapsed;
                choosePhotoButton.Visibility = Visibility.Collapsed;
                uploadPhotoButton.Visibility = Visibility.Visible;
                cancelButton.Visibility = Visibility.Visible;
                savePhotoButton.Visibility = Visibility.Visible;

                // Convert Image to byte-array
                //byte[] b = new byte[e.ChosenPhoto.Length];
                //e.ChosenPhoto.Read(b, 0, Convert.ToInt32(e.ChosenPhoto.Length));


                // not needed code:
                /*var img = new BitmapImage();
                img.SetSource(e.ChosenPhoto);
                //loadedImg.Source = img;*/
                ReadExif(info);
            }
            else
            {
            }
        }


        public void ReadExif(JpegInfo info)
        {
            MessageBox.Show("Artist: " + info.Artist
        + "\n Copyright: " + info.Copyright
        + "\n Datetime: " + info.DateTime
        + "\n Description: " + info.Description
        + "\n Exposure: " + info.ExposureTime
        + "\n File name: " + info.FileName
        + "\n File size: " + info.FileSize
        + "\n Flash: " + info.Flash
        + "\n F number: " + info.FNumber
        + "\n GPS Latitude: " + info.GpsLatitude[0].ToString() + "." + info.GpsLatitude[1].ToString() + "\"" + info.GpsLatitude[2].ToString()
        + "\n GPS Latitude ref: " + info.GpsLatitudeRef
        + "\n GPS Longitude: " + info.GpsLongitude[0].ToString() + "." + info.GpsLongitude[1].ToString() + "\"" + info.GpsLongitude[2].ToString()
        + "\n GPS Longitude ref: " + info.GpsLongitudeRef
        + "\n Height: " + info.Height
        + "\n Is color: " + info.IsColor
        + "\n Is valid: " + info.IsValid
        + "\n Load time: " + info.LoadTime
        + "\n Make: " + info.Make
        + "\n Orientation: " + info.Orientation
        + "\n Resolution unit: " + info.ResolutionUnit
        + "\n Software: " + info.Software
        + "\n Thumbnail data: " + info.ThumbnailData
        + "\n Thumbnail offset: " + info.ThumbnailOffset
        + "\n Thumbnail size: " + info.ThumbnailSize
        + "\n User comment: " + info.UserComment
        + "\n Width: " + info.Width
        + "\n X resolution: " + info.XResolution
        + "\n Y resolution: " + info.YResolution);
            //EXIFLocation.Text = "Lat: " + info.GpsLatitude[0].ToString() + "." + info.GpsLatitude[1].ToString() + "\"" + info.GpsLatitude[2].ToString() + " | " + "Long: " + info.GpsLongitude[0].ToString() + "." + info.GpsLongitude[1].ToString() + "\"" + info.GpsLongitude[2].ToString();
        }

        private void uploadPhotoButton_Click(object sender, EventArgs e)
        {
            InputPrompt input = new InputPrompt();
            input.Completed += input_Completed;
            input.Title = "Title";
            input.Message = "Please enter a title for your upload";
            input.Show();
            //NavigationService.Navigate(new Uri("//UploadPage.xaml", UriKind.Relative));          
        }

        void input_Completed(object sender, PopUpEventArgs<string, PopUpResult> e)
        {
            if (e.PopUpResult == PopUpResult.Ok)
            {
                titleinput = e.Result;
                InputPrompt input2 = new InputPrompt();
                input2.Completed += input_Completed2;
                input2.Title = "Description";
                input2.Message = "Please enter a description for your upload";
                input2.Show();
            }
            else if (e.PopUpResult == PopUpResult.Cancelled)
            {
                MessageBox.Show("Cancelled: " + e.Result);
            }
            else
                MessageBox.Show("Else: " + e.Result);
        }

        void input_Completed2(object sender, PopUpEventArgs<string, PopUpResult> e)
        {
            if (e.PopUpResult == PopUpResult.Ok)
            {
                descinput = e.Result;
                GlobalVariables.title = titleinput;
                GlobalVariables.desc = descinput;
                MessageBox.Show("Title: " + titleinput + " - Desc: " + descinput);
                NavigationService.Navigate(new Uri("//UploadPage.xaml?title=" + titleinput + "&desc=" + descinput, UriKind.Relative));
            }
            else if (e.PopUpResult == PopUpResult.Cancelled)
            {
                MessageBox.Show("Cancelled: " + e.Result);
            }
            else
                MessageBox.Show("Else: " + e.Result);
        }




        private void cancelButton_Click(object sender, EventArgs e)
        {
            myImage.Source = null;
            // swap UI element states
            takePhotoButton.Visibility = Visibility.Visible;
            choosePhotoButton.Visibility = Visibility.Visible;
            uploadPhotoButton.Visibility = Visibility.Collapsed;
            cancelButton.Visibility = Visibility.Collapsed;
            doneButton.Visibility = Visibility.Collapsed;
            savePhotoButton.Visibility = Visibility.Collapsed;
            EXIFLocation.Visibility = Visibility.Collapsed;
            
        }

        // Foto speichern
        private void savePhotoButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                // Dateinamen für JPEG-Datei im temporären Speicher
                String tempJPEG = "TempJPEG";

                // File-Stream (+ check, ob temporäre Datei schon vorhanden)
                var myStore = IsolatedStorageFile.GetUserStoreForApplication();
                if (myStore.FileExists(tempJPEG))
                {
                    myStore.DeleteFile(tempJPEG);
                }

                IsolatedStorageFileStream myFileStream = myStore.CreateFile(tempJPEG);


                // Create a stream out of the sample JPEG file.
                // The use of TempJPEG was established earlier.
                Uri uri = new Uri("geopg_wp7;component/TempJPEG.jpg", UriKind.Relative);

                // Create a new WriteableBitmap object and set it to the JPEG stream.
                WriteableBitmap wb = new WriteableBitmap(bmp);


                // Bitmap in JPEG codieren
                // SaveJpeg(WriteableBitmap bitmap, Stream targetStream, int targetWidth, 
                //     int targetHeight, int orientation, int quality)
                System.Windows.Media.Imaging.Extensions.SaveJpeg(wb, myFileStream, wb.PixelWidth, wb.PixelHeight, 0, 85);
                myFileStream.Close();


                // File-Stream und JPEG in "media library" von Windows Phone speichern
                myFileStream = myStore.OpenFile(tempJPEG, FileMode.Open, FileAccess.Read);

                MediaLibrary library = new MediaLibrary();
                Picture pic = library.SavePicture("SavedPicture.jpg", myFileStream);
                myFileStream.Close();
                savePhotoButton.IsEnabled = false;
                cancelButton.Visibility = Visibility.Collapsed;
                doneButton.Visibility = Visibility.Visible;
                MessageBox.Show("Saved picture!");
            }
            catch (Exception myError)
            {
                MessageBox.Show(myError.Message);
            }
        }

        private void takePhotoButton_Click(object sender, EventArgs e)
        {
            cameraCaptureTask.Show();
        }

        private void choosePhotoButton_Click(object sender, EventArgs e)
        {
            photoChooserTask.Show();
            savePhotoButton.IsEnabled = true;
        }

        private void mainPage_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("//MainPage.xaml", UriKind.Relative));
        }

        private void localPictures_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("//LocalPicturesPage.xaml", UriKind.Relative));
        }

        private void settings_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("//SettingsPage.xaml", UriKind.Relative));
        }

        private void info_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("//InfoPage.xaml", UriKind.Relative));
        }

        private void login_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("//LoginPage.xaml", UriKind.Relative));
        }

        private void logout_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("//LogoutPage.xaml", UriKind.Relative));
        }

        public void register_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("//RegisterPage.xaml", UriKind.Relative));
        }

        private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
        {

        }


    }
}